#include "../head.h"

int main()
{
    printf("服务器start\n");
    //  1.创建套接字
    int sockfd;
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket error");
        return -1;
    }
    // 2.设置地址结构体
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(6153);
    server_addr.sin_addr.s_addr = inet_addr("192.168.47.198");
    // 3.绑定ip地址和端口号
    bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    // 4.定义结构体存储对方的ip和端口
    struct sockaddr_in client_addr;
    int len = sizeof(struct sockaddr_in);
    // 5.接收数据
    while (1)
    {
        char buf[1024];
        int ret = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&client_addr, &len);
        if (ret < 0)
        {
            perror("recvfrom error");
            break;
        }
        printf("client ip: %s, port: %d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
        printf("接收数据: %s\n", buf);
        sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&client_addr, len);
    }
    
    close(sockfd); 
    return 0;
}